package com.shiku.imclient;

import com.shiku.imserver.common.message.AbstractMessage;
import com.shiku.imserver.common.message.AuthMessage;
import com.shiku.imserver.common.message.ChatMessage;
import com.shiku.imserver.common.message.JoinGroupMessage;
import com.shiku.imserver.common.message.MessageHead;
import com.shiku.imserver.common.packets.ImPacket;
import com.shiku.imserver.common.proto.MessageProBuf;
import com.shiku.imserver.common.tcp.TcpPacket;
import com.shiku.imserver.common.utils.ProBufUtils;
import com.shiku.imserver.common.utils.StringUtils;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.core.ChannelContext;
import org.tio.core.Node;
import org.tio.core.Tio;

public class BaseIMClient {
    protected static final Logger log = LoggerFactory.getLogger(BaseIMClient.class);
    protected BaseClientHandler clientHandler;
    protected BaseClientListener clientListener;
    protected String connStr = "10005/Server";
    protected ClientChannelContext context;
    protected ScheduledThreadPoolExecutor executor;
    protected boolean isAuth = false;
    protected SendMessageReceiptRunnable messageReceiptRunnable;
    protected long pingTime = 60000;
    protected String resource = "Server";
    protected Node serverNode;
    protected TioClient tioClient;
    protected String userId = "10005";

    public void setISAuth(boolean auth) {
        this.isAuth = auth;
    }

    public boolean getISAuth() {
        return this.isAuth;
    }

    public BaseClientHandler getClientHandler() {
        return this.clientHandler;
    }

    public void setExecutor(ScheduledThreadPoolExecutor executor2) {
        this.executor = executor2;
    }

    public ScheduledThreadPoolExecutor getExecutor() {
        return this.executor;
    }

    public TioClient getTioClient() {
        return this.tioClient;
    }

    public void initIMClient(String ip, int port, BaseClientHandler clientHandler2, BaseClientListener clientListener2) throws Exception {
        this.serverNode = new Node(ip, port);
        this.clientHandler = clientHandler2;
        this.clientListener = clientListener2;
        initHandlerListener();
        this.connStr = this.userId + "/" + this.resource;
        this.context = getClientChannelContext();
        this.messageReceiptRunnable = new SendMessageReceiptRunnable(this);
        if (this.context != null) {
            this.context.userid = this.userId;
            Tio.bindUser(this.context, this.userId);
            Tio.bindToken(this.context, this.connStr);
        }
    }

    public void connect() throws Exception {
        this.tioClient.connect(this.serverNode);
    }

    public void login() {
        sendMessage(this.clientListener.authUserMessage(this.context, this));
    }

    public void joinGroup(String jid) {
        MessageHead messageHead = createMessageHead((byte) 2, jid);
        JoinGroupMessage message = new JoinGroupMessage();
        message.setJid(jid);
        message.setSeconds(0);
        message.setMessageHead(messageHead);
        TcpPacket packet = ProBufUtils.encodeTcpPacket(message, MessageProBuf.JoinGroupMessageProBuf.getDescriptor());
        packet.setCommand((short)20);
        sendImPacket(packet);
    }

    public MessageHead createMessageHead(byte chatType, String to) {
        MessageHead messageHead = new MessageHead();
        messageHead.setFrom(this.connStr);
        messageHead.setMessageId(StringUtils.newStanzaId());
        messageHead.setTo(to);
        messageHead.setChatType(chatType);
        return messageHead;
    }

    /* access modifiers changed from: package-private */
    public void initHandlerListener() {
        if (this.clientHandler == null) {
            this.clientHandler = new BaseClientHandler() {
                /* class com.shiku.imclient.BaseIMClient.AnonymousClass1 */

                public void handlerReceipt(String messageId) {
                }
            };
        }
        if (this.clientListener == null) {
            this.clientListener = new BaseClientListener() {
                /* class com.shiku.imclient.BaseIMClient.AnonymousClass2 */

                public AuthMessage authUserMessage(ChannelContext channelContext, BaseIMClient imClient) {
                    return null;
                }
            };
        }
    }

    public void initIMClient(String ip, int port) {
        try {
            initIMClient(ip, port, this.clientHandler, this.clientListener);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    public ClientGroupContext getClientGroupContext() {
        return new ClientGroupContext(this.clientHandler, this.clientListener, new ReconnConf(5000));
    }

    public ClientChannelContext getClientChannelContext() throws Exception {
        try {
            ClientGroupContext context2 = getClientGroupContext();
            context2.setHeartbeatTimeout(this.pingTime);
            this.tioClient = new TioClient(context2);
            ClientChannelContext clientChannel = this.tioClient.connect(this.serverNode);
            if (clientChannel == null) {
                log.error("getClientChannelContext  connect Server fail ====>");
            }
            return clientChannel;
        } catch (Exception e) {
            throw e;
        }
    }

    public boolean isSendOk() {
        return this.clientHandler.isSendOk();
    }

    public void setSendOk(boolean sendOk) {
        this.clientHandler.setSendOk(sendOk);
    }

    public ImPacket createPingPacket() {
        return this.clientHandler.createPingPacket(this.context);
    }

    public void sendMessage(ChatMessage message, byte chatType) {
        if (message.getMessageHead() == null) {
            message.setMessageHead(createMessageHead(chatType, message.getToUserId()));
        }
        sendMessage(message);
    }

    /**
     * 发生消息到tcp服务
     * @param message
     */
    public void sendMessage(AbstractMessage message) {
        setSendOk(false);
        TcpPacket packet = ProBufUtils.encodeTcpPacket(message, MessageProBuf.ChatMessage.getDescriptor());
        packet.setCommand((short)10);
        Tio.send(getContext(), packet);
    }

    public void sendBlockMessage(AbstractMessage message) {
        setSendOk(false);
        TcpPacket packet = ProBufUtils.encodeTcpPacket(message, MessageProBuf.ChatMessage.getDescriptor());
        packet.setCommand((short)10);
        Tio.bSend(getContext(), packet);
    }

    public void sendImPacket(ImPacket imPacket) {
        setSendOk(false);
        Tio.send(getContext(), new TcpPacket(imPacket.getCommand(), imPacket.getBytes()));
    }

    public AbstractMessage createMessage(String to, short type, String content) {
        ChatMessage message = new ChatMessage();
        MessageHead head = new MessageHead();
        head.setChatType((byte) 1);
        head.setMessageId(StringUtils.newStanzaId());
        head.setFrom(this.userId + "/Server");
        head.setTo(to);
        message.setMessageHead(head);
        message.setType(type);
        message.setFromUserId(this.userId);
        message.setToUserId(to);
        message.setContent(content);
        return message;
    }

    public void sendMessageReceipt(AbstractMessage message) {
        this.messageReceiptRunnable.putMessageReceipt(message.getMessageHead().getMessageId());
    }

    public void stop() {
        this.tioClient.stop();
    }

    public void setPingTime(long pingTime2) {
        this.pingTime = pingTime2;
    }

    public void setResource(String resource2) {
        this.resource = resource2;
    }

    public void setUserId(String userId2) {
        this.userId = userId2;
    }

    public String getUserId() {
        return this.userId;
    }

    public String getResource() {
        return this.resource;
    }

    public String getConnStr() {
        return this.connStr;
    }

    public ClientChannelContext getContext() {
        return this.context;
    }
}
